package org.jeecg.modules.xl.as.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.xl.as.entity.XlCustomerAsDetail;
import org.jeecg.modules.xl.as.mapper.XlCustomerAsMapper;
import org.jeecg.modules.xl.as.service.IXlCustomerAsDetailService;
import org.jeecg.modules.xl.as.service.IXlCustomerAsService;
import org.jeecg.modules.xl.as.vo.ASAddRequest;
import org.jeecg.modules.xl.as.vo.ASDetailAddVo;
import org.jeecg.modules.xl.common.XlLogUtil;
import org.jeecg.modules.xl.order.entity.XlCustomerOrde;
import org.jeecg.modules.xl.order.entity.XlCustomerOrderDetail;
import org.jeecg.modules.xl.order.service.IXlCustomerOrdeService;
import org.jeecg.modules.xl.product.entity.XlProductInfo;
import org.jeecg.modules.xl.product.service.IXlProductInfoService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.jeecg.modules.xl.as.entity.XlCustomerAs;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * ${DESCRIPTION}
 * @author deco
 * @create 2025-03-15
*/
@Service
public class XlCustomerAsServiceImpl extends ServiceImpl<XlCustomerAsMapper, XlCustomerAs> implements IXlCustomerAsService {

    @Resource
    private IXlCustomerAsDetailService xlCustomerAsDetailService;
    @Resource
    private XlLogUtil xlLogUtil;
    @Resource
    private IXlCustomerOrdeService ordeService;

    @Resource
    private IXlProductInfoService productInfoService;
    @Value("${pichost}")
    private String baseUrl;

    @Override
    public IPage<XlCustomerAs> getASListByPage(String listType, String orderCode, String storeCode, Integer pageNo, Integer pageSize) {
        QueryWrapper<XlCustomerAs> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("store_code",storeCode);
        queryWrapper.orderByDesc("create_time");
        if(ObjectUtil.isNotEmpty(orderCode)){
            queryWrapper.eq("as_code",orderCode);
        }
        if("待处理".equals(listType)){
            queryWrapper.in("as_status", Arrays.asList("待审核", "退款中"));
        }
        IPage<XlCustomerAs> page = new Page<XlCustomerAs>(pageNo, pageSize);
        IPage<XlCustomerAs> sss = baseMapper.selectPage(page,queryWrapper);
        //处理凭证图片
        for(XlCustomerAs xlCustomerAs : sss.getRecords()) {
            xlCustomerAs.setTotalAmount(xlCustomerAs.getApplyAmount());
//            String pzpics = xlCustomerAs.getApplyAttachments();
//            String newr = Arrays.stream(pzpics.split(",")).map(path -> baseUrl + path).collect(Collectors.joining(","));
//            xlCustomerAs.setApplyAttachments(newr);
            if(StrUtil.containsAny(xlCustomerAs.getAsType(),"退货")){
                xlCustomerAs.setReturnAddress("广东省黄埔区永盛路30号C座2楼");
                xlCustomerAs.setReturnPhone("17751142381");
                xlCustomerAs.setReturnContact("好特麦退货");
            }
        }
        return sss;
    }


    @Override
    public List<XlCustomerAsDetail> getAsDetailByASCode(String asCode) {
        QueryWrapper<XlCustomerAsDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("as_code",asCode);
        return xlCustomerAsDetailService.list(queryWrapper);
    }

    @Override
    public Result<String> addAs(ASAddRequest asAddRequest) {
        String orderCode = asAddRequest.getOrderCode();
        //校验订单有效性
        XlCustomerOrde orde = ordeService.getOneByCode(orderCode);
        List<XlCustomerOrderDetail> details= ordeService.getDetailByCode(orderCode);
        Map<String,XlCustomerOrderDetail> orderDetailMap=  details.stream().collect(Collectors.toMap(XlCustomerOrderDetail::getUpcCode
                , Function.identity(),(existing,replacement) -> existing ));
        if(ObjectUtil.isAllEmpty(orde,details)){
            return Result.error("订单数据异常,请核实");
        }

        // 校验退货明细商品明细

        String asCode = "SHWX"+orderCode+ RandomUtil.randomNumbers(3);
        String asType = asAddRequest.getAsType();

        //仅退款-整单退
        //仅退款-部分退
        //退货退款-整单退
        //退货退款-部分退
        XlCustomerAs as =new XlCustomerAs();
        as.setAsCode(asCode);
        as.setAsStatus("待审核");
        as.setAsNotes(asAddRequest.getAsNotes());
        as.setApplyAmount(asAddRequest.getTotalAmount());
        BeanUtil.copyProperties(asAddRequest,as);
        baseMapper.insert(as);

        /**商品总数量*/
        Double totalNum = Double.valueOf(0);
        /**商品种数*/
        Integer detailNum = 0;
        /**订单总金额*/
        Double totalAmount = 0.00;


        if("仅退款-整单退".equals((asType))||"退货退款-整单退".equals(asType)){

            //如果是整单退,不用填写数量，把订单里的明细作为退货明细进行报错
            for(XlCustomerOrderDetail orderDetail : details){

                XlCustomerAsDetail asDetailEntity = new XlCustomerAsDetail();
                asDetailEntity.setAsId(as.getAsId());
                asDetailEntity.setAsCode(asCode);
                asDetailEntity.setOrderCode(orderCode);
                asDetailEntity.setOrderDetailId(Long.valueOf(orderDetail.getId()));
                XlProductInfo  productInfo = productInfoService.getProductInfoCacheable(orderDetail.getUpcCode());
                asDetailEntity.setUpcCode(orderDetail.getUpcCode());
                asDetailEntity.setProductName(productInfo.getProductName());
                asDetailEntity.setProductPrice(orderDetail.getProductPrice());
                asDetailEntity.setAsQuantity(orderDetail.getOrderQuantity().intValue());
                asDetailEntity.setAsAmount(orderDetail.getOrderAmount());
                asDetailEntity.setProductMainPic(productInfo.getMainPic());
                xlCustomerAsDetailService.save(asDetailEntity);

                totalNum +=asDetailEntity.getAsQuantity();
                detailNum++;
                totalAmount += asDetailEntity.getAsAmount().doubleValue();

            }
        }else{
            //部分退货
            List<ASDetailAddVo> detailadd = asAddRequest.getDetails();

            for(ASDetailAddVo add : detailadd){
                XlCustomerAsDetail asDetailEntity = new XlCustomerAsDetail();

                BeanUtil.copyProperties(add,asDetailEntity);

                asDetailEntity.setAsId(as.getAsId());
                asDetailEntity.setAsCode(asCode);
                asDetailEntity.setOrderCode(orderCode);

                XlCustomerOrderDetail orderDetailTemp = orderDetailMap.get(add.getUpcCode());
                asDetailEntity.setOrderDetailId(Long.valueOf(orderDetailTemp.getId()));
                XlProductInfo  productInfo = productInfoService.getProductInfoCacheable(add.getUpcCode());
                asDetailEntity.setProductName(productInfo.getProductName());
                asDetailEntity.setAsAmount(asDetailEntity.getProductPrice().multiply(BigDecimal.valueOf(add.getAsQuantity())));
                asDetailEntity.setProductMainPic(productInfo.getMainPic());
                xlCustomerAsDetailService.save(asDetailEntity);

                totalNum +=asDetailEntity.getAsQuantity();
                detailNum++;
                totalAmount += asDetailEntity.getAsAmount().doubleValue();
            }
        }
        as.setProductTotalAmount(BigDecimal.valueOf(totalAmount));
        as.setProductCategoryCount(detailNum);
        as.setProductTotalQuantity(totalNum.intValue());
        baseMapper.updateById(as);
        xlLogUtil.insertLog(as.getAsCode(),"售后提交","小程序发起售后",new Date(),"","待审核");

        return Result.ok("提交成功");
    }
}
